import 'dart:convert';
import 'dart:math';

import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:miuu_note_app/model/msg_entity.dart';

import '../dao/todo_dao.dart';
import '../model/todo_entity.dart';
import 'todo_add_update.dart';

class HomePage extends StatefulWidget {
  const HomePage({
    Key? key,
  }) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with SingleTickerProviderStateMixin {
  String testContent = '正在获取数据';
  List<TodoModel> _todos = [];
  List<BadgeTab> tabs = [BadgeTab(text: "未完成"), BadgeTab(text: "已完成")];
  TabController? tabController;

  @override
  void initState() {
    super.initState();
    _getTodoList({'itemStatus': false});
    tabController = TabController(length: tabs.length, vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            floatingActionButton: FloatingActionButton(
              heroTag: 'addTodo',
              onPressed: () {
                Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => const TodoEdit())).then((value) {
                  if (value != null) {
                    _getTodoList({'itemStatus': false});
                  }
                });
                setState(() {
                  // if (_selectedEvents.length < 50) {
                  //   _selectedEvents.add('新事件s ${_selectedEvents.length + 1}');
                  //   print(_selectedEvents);
                  // }
                });
              },
              child: const Icon(Icons.add),
            ),
            backgroundColor: const Color.fromARGB(255, 249, 250, 252),
            appBar: BrnAppBar(
              automaticallyImplyLeading: false,
              themeData: BrnAppBarConfig.light(),
              title: '每日待办',
            ),
            body: ListView(
              padding: const EdgeInsets.symmetric(vertical: 20),
              children: [
                Container(
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(10),
                      color: Colors.white),
                  margin:
                      const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                  padding:
                      const EdgeInsets.symmetric(horizontal: 5, vertical: 10),
                  child: Column(
                    children: [
                      BrnTabBar(
                        tabs: tabs,
                        onTap: (state, index) {
                          _getTodoList({'itemStatus': index == 1});
                          state.refreshBadgeState(index);
                        },
                        controller: tabController,
                      ),
                      ListView.separated(
                        separatorBuilder: (_, __) => const SizedBox(
                          height: 5,
                        ),
                        itemCount: _todos.length,
                        padding: const EdgeInsets.symmetric(
                            horizontal: 0, vertical: 10),
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        itemBuilder: (context, index) {
                          TodoModel item = _todos[index];
                          return ListTile(
                            trailing: GestureDetector(
                              child: const Icon(
                                Icons.edit_note,
                                size: 30,
                                color: Color.fromARGB(255, 210, 210, 210),
                              ),
                              onTapUp: (value) {
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) => const TodoEdit(),
                                      settings: RouteSettings(
                                          name: '编辑待办',
                                          arguments:
                                              jsonEncode(item)) // 需要跳转的页面
                                      ),
                                ).then((value) {
                                  if (value != null) {
                                    _getTodoList({'itemStatus': false});
                                  }
                                });
                              },
                            ),
                            leading: Checkbox(
                                activeColor:
                                    const Color.fromARGB(255, 194, 194, 194),
                                checkColor:
                                    const Color.fromARGB(255, 255, 255, 255),
                                value: item.itemStatus,
                                onChanged: (value) {
                                  item.itemStatus = value!;
                                  _updateTodo(item.toJson());
                                }),
                            title: Text(item.title ?? ''),
                            subtitle: Text(item.todoDate ?? ''),
                          );
                        },
                      ),
                    ],
                  ),
                ),
              ],
            )));
  }

  void _getTodoList(Map<String, dynamic> map) async {
    TodoListEntity? entity = await TodoListDao.fetch(map);
    setState(() {
      _todos = entity!.todos;
      _getCountTodo({'itemStatus': false});
    });
  }

  void _getCountTodo(Map<String, dynamic> map) async {
    MsgEntity? msgEntity = await TodoGetCountDao.fetch(map);
    if (msgEntity?.msgModel.code == 200) {
      setState(() {
        tabs = [
          BadgeTab(text: "未完成", badgeNum: int.parse(msgEntity!.msgModel.data!)),
          BadgeTab(
            text: "已完成",
          )
        ];
      });
    }
  }

  void _updateTodo(Map<String, dynamic> map) async {
    MsgEntity? msgEntity = await TodoUpdateDao.fetch(map);
    if (msgEntity?.msgModel.code == 200) {
      _getTodoList({'itemStatus': !map['itemStatus']});
    }
  }
}

void getHttp() async {}

void doNothing(BuildContext context) async {}
